package problem54;

//54.螺旋矩阵
//https://leetcode.cn/problems/spiral-matrix/

import java.util.ArrayList;
import java.util.List;

class Solution {
    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        int left = 0, right = matrix[0].length-1;
        int top = 0, bottom = matrix.length-1;
        while(true) {
            //遍历顶行
            for(int i = left; i<=right; i++) {
                list.add(matrix[top][i]);
            }
            top++;
            if(top > bottom) break;

            //遍历右列
            for(int i = top; i<= bottom; i++) {
                list.add(matrix[i][right]);
            }
            right--;
            if(left > right) break;

            //遍历底行
            for(int i = right; i>=left; i--) {
                list.add(matrix[bottom][i]);
            }
            bottom--;
            if(top > bottom) break;

            //遍历左列
            for(int i = bottom; i>=top; i--) {
                list.add(matrix[i][left]);
            }
            left++;
            if(left > right) break;
        }
        return list;
    }
}